<template>
  <div class="user-manage-container">
    <h1 class="page-title">用户管理</h1>
    
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="showCreateUserDialog = true">
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索用户名或邮箱"
        prefix-icon="el-icon-search"
        style="width: 300px; margin-left: 20px;"
        @input="handleSearch"
      />
    </div>

    <!-- 用户列表 -->
    <el-table
      v-loading="loading"
      :data="filteredUsers"
      style="width: 100%; margin-top: 20px;"
      border
    >
      <el-table-column prop="UserName" label="用户名" width="180" />
      <el-table-column prop="Email" label="邮箱" width="250" />
      <el-table-column prop="FullName" label="姓名" />
      <el-table-column prop="Roles" label="角色" width="200">
        <template #default="scope">
          <el-tag v-for="role in scope.row.Roles" :key="role" size="small" style="margin-right: 5px;">
            {{ role }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="IsLockedOut" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.IsLockedOut ? 'danger' : 'success'" disable-transitions>
            {{ scope.row.IsLockedOut ? '锁定' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editUser(scope.row)">
            编辑
          </el-button>
          <el-button size="small" @click="resetUserPassword(scope.row)">
            重置密码
          </el-button>
          <el-button 
            v-if="scope.row.IsLockedOut" 
            type="success" 
            size="small" 
            @click="handleUnlockUser(scope.row)"
          >
            解锁
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDeleteUser(scope.row)"
            :disabled="scope.row.UserName === currentUserName"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; justify-content: flex-end;"
    />

    <!-- 创建用户对话框 -->
    <el-dialog
      v-model="showCreateUserDialog"
      title="创建新用户"
      width="600px"
    >
      <el-form :model="createUserForm" :rules="createUserRules" ref="createUserRef" label-width="100px">
        <el-form-item label="用户名" prop="UserName">
          <el-input v-model="createUserForm.UserName" />
        </el-form-item>
        <el-form-item label="姓名" prop="FullName">
          <el-input v-model="createUserForm.FullName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="Email">
          <el-input v-model="createUserForm.Email" type="email" />
        </el-form-item>
        <el-form-item label="密码" prop="Password">
          <el-input v-model="createUserForm.Password" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="Roles">
          <el-select v-model="createUserForm.Roles" multiple placeholder="请选择角色">
            <el-option
              v-for="role in roles"
              :key="role.Id"
              :label="role.Name"
              :value="role.Name"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateUserDialog = false">取消</el-button>
        <el-button type="primary" @click="submitCreateUser">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="showEditUserDialog"
      title="编辑用户"
      width="600px"
    >
      <el-form :model="editUserForm" :rules="editUserRules"
       label-position="top"
       ref="editUserRef"
       label-width="100px">
        <el-form-item label="用户名" disabled>
          <el-input v-model="editUserForm.UserName" disabled />
        </el-form-item>
        <el-form-item label="邮箱" prop="Email">
          <el-input v-model="editUserForm.Email" type="email" />
        </el-form-item>
        <el-form-item label="姓名" prop="FullName">
          <el-input v-model="editUserForm.FullName" />
        </el-form-item>
        <el-form-item label="角色" prop="Roles">
          <el-select v-model="editUserForm.Roles" multiple placeholder="请选择角色">
            <el-option
              v-for="role in roles"
              :key="role.Id"
              :label="role.Name"
              :value="role.Name"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditUserDialog = false">取消</el-button>
        <el-button type="primary" @click="submitEditUser">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="showResetPasswordDialog"
      title="重置密码"
      width="400px">   
      <el-form :model="resetPasswordForm" :rules="resetPasswordRules"
       label-position="top"
       ref="resetPasswordRef" label-width="80px">
        <el-form-item >
        <el-icon><User></User></el-icon> &nbsp;
         {{ selectedUser?.UserName }}
        </el-form-item>   
        <el-form-item label="新密码" prop="NewPassword">
          <el-input v-model="resetPasswordForm.NewPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showResetPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="submitResetPassword">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import {
  getUsers,
  createUser,
  updateUser,
  deleteUser as deleteUserApi,
  resetPassword,
  unlockUser as unlockUserApi,
  getRoles,
  getApiError,
  type AdminUserViewModel,
  type AdminCreateUserModel,
  type AdminUpdateUserModel,
  type AdminResetPasswordModel,
  type PagingParams,
  type RoleViewModel
} from '../api/auth.service';

// 状态管理
const loading = ref(false);
const users = ref<AdminUserViewModel[]>([]);
const roles = ref<RoleViewModel[]>([]);
const searchQuery = ref('');
const currentUserName = ref(''); // 当前登录用户，用于防止删除自己

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  totalCount: 0
});

// 对话框状态
const showCreateUserDialog = ref(false);
const showEditUserDialog = ref(false);
const showResetPasswordDialog = ref(false);
const selectedUser = ref<AdminUserViewModel | null>(null);

// 创建用户表单
const createUserForm = ref<AdminCreateUserModel>({
  UserName: '',
  Email: '',
  Password: '',
  FullName: '',
  Roles: []
});

const createUserRules = {
  UserName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  Email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  Password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  FullName: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
};

const createUserRef = ref();

// 编辑用户表单
const editUserForm = ref<AdminUpdateUserModel & { UserName: string }>({
  UserName: '',
  Email: '',
  FullName: '',
  Roles: []
});

const editUserRules = {
  Email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  FullName: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
};

const editUserRef = ref();

// 重置密码表单
const resetPasswordForm = ref<AdminResetPasswordModel>({
  UserId: '',
  NewPassword: ''
});

const resetPasswordRules = {
  NewPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }]
};

const resetPasswordRef = ref();

// 计算属性：过滤后的用户列表
const filteredUsers = computed(() => {
  if (!searchQuery.value) {
    return users.value;
  }
  const query = searchQuery.value.toLowerCase();
  return users.value.filter(user => 
    user.UserName.toLowerCase().includes(query) || 
    user.Email.toLowerCase().includes(query)
  );
});

// 加载用户列表
const loadUsers = async () => {
  loading.value = true;
  try {
    const params: PagingParams = {
      pageNumber: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    };
    const result = await getUsers(params);
    users.value = result.Data;
    pagination.value.totalCount = result.TotalCount;
  } catch (error) {
    ElMessage.error(`加载用户列表失败: ${getApiError(error)}`);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1;
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  loadUsers();
};

// 处理页码变化
const handleCurrentChange = (current: number) => {
  pagination.value.currentPage = current;
  loadUsers();
};

// 打开编辑用户对话框
const editUser = (user: AdminUserViewModel) => {
  selectedUser.value = user;
  editUserForm.value = {
    UserName: user.UserName,
    Email: user.Email,
    FullName: user.FullName,
    Roles: [...user.Roles]
  };
  showEditUserDialog.value = true;
};

// 提交编辑用户
const submitEditUser = async () => {
  if (!editUserRef.value) return;
  
  const valid = await editUserRef.value.validate();
  if (!valid) return;
  
  if (!selectedUser.value) return;
  
  try {
    await updateUser(selectedUser.value.Id, editUserForm.value);
    ElMessage.success('用户信息更新成功');
    showEditUserDialog.value = false;
    loadUsers();
  } catch (error) {
    ElMessage.error(`更新用户失败: ${getApiError(error)}`);
  }
};

// 提交创建用户
const submitCreateUser = async () => {
  if (!createUserRef.value) return;
  
  const valid = await createUserRef.value.validate();
  if (!valid) return;
  
  try {
    await createUser(createUserForm.value);
    ElMessage.success('用户创建成功');
    showCreateUserDialog.value = false;
    createUserForm.value = {
      UserName: '',
      Email: '',
      Password: '',
      FullName: '',
      Roles: []
    };
    loadUsers();
  } catch (error) {
    ElMessage.error(`创建用户失败: ${getApiError(error)}`);
  }
};

// 打开重置密码对话框
const resetUserPassword = (user: AdminUserViewModel) => {
  selectedUser.value = user;
  resetPasswordForm.value = {
    UserId: user.Id,
    NewPassword: ''
  };
  showResetPasswordDialog.value = true;
};

// 提交重置密码
const submitResetPassword = async () => {
  if (!resetPasswordRef.value) return;
  
  const valid = await resetPasswordRef.value.validate();
  if (!valid) return;
  
  try {
    await resetPassword(resetPasswordForm.value);
    ElMessage.success('密码重置成功');
    showResetPasswordDialog.value = false;
  } catch (error) {
    ElMessage.error(`重置密码失败: ${getApiError(error)}`);
  }
};

// 解锁用户
const handleUnlockUser = async (user: AdminUserViewModel) => {
  try {
    await unlockUserApi(user.Id);
    ElMessage.success('用户解锁成功');
    loadUsers();
  } catch (error) {
    ElMessage.error(`解锁用户失败: ${getApiError(error)}`);
  }
};

// 删除用户
const handleDeleteUser = async (user: AdminUserViewModel) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.UserName}" 吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await deleteUserApi(user.Id);
    ElMessage.success('用户删除成功');
    loadUsers();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`删除用户失败: ${getApiError(error)}`);
    }
  }
};

// 加载角色列表
const loadRoles = async () => {
  try {
    roles.value = await getRoles();
  } catch (error) {
    ElMessage.error(`加载角色列表失败: ${getApiError(error)}`);
  }
};

// 初始化
onMounted(() => {
  loadUsers();
  loadRoles();
});
</script>

<style scoped>
.user-manage-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #e5e7eb;
}

.action-bar {
  display: flex;
  align-items: center;
  background-color: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header-wrapper) {
  background-color: #f8fafc;
}

:deep(.el-table__header th) {
  font-weight: 600;
  color: #4b5563;
}

:deep(.el-pagination) {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

</style>